/**
 * Copyright (c) 2010-2011 by Kevin Bierhoff.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *    3. Neither the names of the authors nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.syper.javasyp.checker;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.SpecASTVisitor;
import org.eclipse.jdt.core.dom.SpecOldExpression;
import org.eclipse.jdt.core.dom.SpecQuantifiedExpression;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.InfixExpression.Operator;

import com.googlecode.syper.javasyp.formulae.Formula;
import com.googlecode.syper.javasyp.formulae.Infix;
import com.googlecode.syper.javasyp.formulae.Local;
import com.googlecode.syper.javasyp.formulae.Pre;
import com.googlecode.syper.javasyp.formulae.Prefix;
import com.googlecode.syper.javasyp.formulae.Quantifier;
import com.googlecode.syper.javasyp.formulae.Ref;


/**
 * Expression encoder for expressions in JML contracts
 * (pre- and post-conditions as well as class invariants).
 * Enables special handling of
 * <ul>
 * <li>{@code \old} and {@code \pre}
 * <li>{@code \forall} and {@code \exists}
 * </ul>
 * @author kevin
 * @since Feb 16, 2011
 */
class JmlExpressionEncoder extends ExpressionEncoder implements SpecASTVisitor {

	/**
	 * Encodes the given expression as a formula using the given lookup callback
	 * @param e
	 * @param lookup
	 * @return the given expression as a formula
	 */
	public static Formula encode(Expression e, Lookup lookup, Lookup preLookup) {
		JmlExpressionEncoder enc = new JmlExpressionEncoder(lookup, preLookup, false);
		return encode(enc, e);
	}

	static Formula encodeStandalone(Expression e, Lookup lookup) {
		JmlExpressionEncoder enc = new JmlExpressionEncoder(lookup, null, true);
		return encode(enc, e);
	}

	private final Lookup preLookup;

	/**
	 * @param lookup
	 * @param standalone
	 */
	private JmlExpressionEncoder(Lookup lookup, Lookup preLookup, boolean standalone) {
		super(lookup, standalone);
		this.preLookup = preLookup;
	}

	@Override
	protected JmlExpressionEncoder newInstance(Lookup newLookup,
			boolean newStandalone) {
		return new JmlExpressionEncoder(newLookup, preLookup, newStandalone);
	}

	@Override
	public boolean visit(SpecOldExpression node) {
		if (node.getLabel() != null)
			throw new UnsupportedOperationException("Cannot encode labeled " + node);
		// little weird... if there is no preLookup, use a Pre formula
		// otherwise use the preLookup directly to avoid having to
		// replace Pre's with their meaning later
		if (preLookup == null) {
			setResult(new Pre((Ref) encodeChild(node.getOperand())));
		} else {
			JmlExpressionEncoder enc = newInstance(preLookup, isStandalone());
			setResult(encode(enc, node.getOperand()));
		}
		return false;
	}

	@Override
	public void endVisit(SpecOldExpression node) {
	}

	@Override
	public boolean visit(SpecQuantifiedExpression node) {
		List<Local> vars = new ArrayList<Local>(node.getBoundVariables().fragments().size());
		for (VariableDeclarationFragment i : (List<VariableDeclarationFragment>) node.getBoundVariables().fragments())
			vars.add(new Local(i.resolveBinding()));

		Formula range = encodeChild(node.getRange(), true);
		Formula pred = encodeChild(node.getExpression(), true /* anonymous inner class expression never available as temp */);
		switch (node.getQuantifier()) {
		case FORALL:
			// forall i . [in-range] ==> pred
			setResult(Quantifier.forall(
				vars,
				Infix.toInfix(Operator.OR,
					Prefix.not(range),
					pred)));
			break;
		case EXISTS:
			// exists i . [in-range] & pred
			setResult(Quantifier.exists(
					vars,
					Infix.toInfix(Operator.AND,
						range,
						pred)));
			break;
		default:
			throw new UnsupportedOperationException("Cannot encode comprehension: " + node.getQuantifier());
		}
		return false;
	}

	@Override
	public void endVisit(SpecQuantifiedExpression node) {
	}
}
